<template>
	<div>
		<div class="header margin-bottom0">
			<el-form size="default" :inline="true">
				<el-form-item label="" class="">
					<el-input v-model="userid" placeholder="请输入用户ID" clearable></el-input>
				</el-form-item>
				<el-form-item label="" class="">
					<el-input v-model="username" placeholder="请输入姓名" clearable></el-input>
				</el-form-item>
				<el-form-item label="成员类型" class="">
					<el-select v-model="userisAdmin" clearable placeholder="请选择" style="width: 220px">
						<el-option v-for="item in type" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="团队组" class="">
					<el-select v-model="teamusergroupid" clearable placeholder="请选择" style="width: 220px">
						<el-option v-for="item in selectGroup" :key="item.name" :label="item.name" :value="item.ID!">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="">
					<el-button @click="start" type="primary" size="default">搜索</el-button>
					<el-button @click="invited" type="primary" size="default">+ 二维码邀请成员</el-button>
					<el-button @click="addUserDialogVisible = true" type="primary" size="default">+ 注册新成员入团队</el-button>
					<el-button @click="addUserListDialogVisible = true" type="primary" size="default">+
						批量添加成员</el-button>
					<div class="online-count margin-left20">
						在线人数(含管理员)：
						<el-popover disabled title="" placement="top-start">
							<template #reference>
								<el-tag type="primary">{{ onlineUser.length }}</el-tag>
							</template>
						</el-popover>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<!-- 编辑用户 -->
		<div>
			<Adduser ref="adduserview" :group="group" :ID="uID" :teamuser="teamuser" :teamid="teamId" :start="start"
				:close="() => (uID = 0)">
			</Adduser>
		</div>
		<!-- 成员列表 -->
		<div class="">
			<el-table :data="tableData" height="68.5vh" style="width: 100%">
				<template v-slot:empty>
					<el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
				</template>
				<el-table-column type="index" width="50"></el-table-column>
				<el-table-column prop="user.name" label="昵称" width="">
					<template #default="{ row }">
						<div class="online-container">
							<div class="online-svg">
								<!-- 在线图标 -->
								<svg v-if="row.online" class="" width="14" height="14" viewBox="0 0 24 24"
									xmlns="http://www.w3.org/2000/svg">
									<defs>
										<linearGradient id="onlineGradient" x1="0%" y1="0%" x2="100%" y2="100%">
											<stop offset="0%" style="stop-color:#4CAF50;stop-opacity:1" />
											<stop offset="100%" style="stop-color:#8BC34A;stop-opacity:1" />
										</linearGradient>
									</defs>
									<circle cx="12" cy="12" r="10" fill="url(#onlineGradient)" />
								</svg>
								<!-- 离线图标 -->
								<svg v-else class="" width="14" height="14" viewBox="0 0 24 24"
									xmlns="http://www.w3.org/2000/svg">
									<circle cx="12" cy="12" r="10" fill="#B0BEC5" />
								</svg>
							</div>
							<span class="username">{{ row?.user?.name }}</span>
						</div>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="username" label="团队内昵称" width=""></el-table-column> -->
				<el-table-column sortable prop="userid" label="用户ID" width="100"></el-table-column>
				<!-- <el-table-column prop="jurisdiction" label="状态" :formatter="({ jurisdiction }) => st[jurisdiction]">
        </el-table-column> -->
				<el-table-column prop="isAdmin" label="类型" :formatter="({ isAdmin }) => { return admin[isAdmin] }"
					width="">
				</el-table-column>
				<el-table-column prop="teamusergroupid" label="团队组"
					:formatter="({ teamusergroupid }) => formatGroupName(teamusergroupid)"> </el-table-column>
				<el-table-column prop="createdAt" label="加入时间" sortable
					:formatter="({ createdAt }) => formatDate(createdAt)">
				</el-table-column>
				<el-table-column prop="context" label="备注" />
				<el-table-column label="操作" width="300">
					<template #default="{ row }">
						<el-button size="default" type="primary" @click="edit(row.ID)">编辑</el-button>
						<el-button size="default" type="primary" @click="delteamuser(row.ID)">移除成员</el-button>
						<el-button size="default" type="danger" @click="resetPwd(row)">重置密码</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination class="pager" :page-size="Number(limit)" :page-sizes="pageSizes" :total="count"
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total,sizes,prev, pager, next">
			</el-pagination>
		</div>
		<!-- 邀请 -->
		<el-dialog title="二维码邀请成员" v-model="dialogVisibleInvited">
			<template #header>
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					二维码邀请成员
				</span>
			</template>
			<div v-loading="invitedLoading">
				<el-form label-width="80px" label-position="top" size="default">
					<!-- 课包选择 -->
					<el-form-item label="选择团队组">
						<el-select v-model="invitedGroup" clearable placeholder="选择团队组" style="width: 220px">
							<el-option v-for="item in group" :key="item.name" :label="item.name" :value="item.ID!">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="选择课包">
						<el-select v-model="courseCatebags" clearable placeholder="选择课包" multiple style="width:50%">
							<el-option v-for="item in allCourseCatebags" :key="`${item.name}-${item.cID}`"
								:label="item.name" :value="item.cID">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="邀请二维码">
						<div>
							<el-button type="primary" size="default" @click="showQrCode">获取团队邀请码</el-button>
						</div>
					</el-form-item>
					<div class="el-error">说明：二维码可以发给未注册用户，用户接受邀请并注册后自动加入当前团队</div>
				</el-form>
			</div>
		</el-dialog>
		<el-dialog class="image-dialog1" title="二维码" v-model="dialogVisibleImage" width="400px">
			<template #header>
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					二维码
				</span>
			</template>
			<img id="canvasimage" width="100%" />
		</el-dialog>

		<!-- 添加成员 -->
		<el-dialog title="添加成员" v-model="addUserDialogVisible" width="800">
			<template #header>
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					注册新成员入团队
				</span>
			</template>
			<el-form :model="addUserForm" label-width="80px" size="large">
				<el-form-item label="姓名">
					<el-input class="add-user-form-item" v-model="addUserForm.name" placeholder="姓名"
						size="default"></el-input>
				</el-form-item>
				<!-- <el-form-item label="昵称">
                <el-input class="add-user-form-item" v-model="addUserForm.name" placeholder="昵称" size="default"></el-input>
            </el-form-item> -->
				<el-form-item label="手机号">
					<el-input class="add-user-form-item" v-model="addUserForm.phonenum" placeholder="手机号" type="number"
						size="default">
					</el-input>
					<el-form-item label="验证码">
						<el-input class="add-user-form-item" v-model="addUserForm.yzm" placeholder="验证码" type="number"
							size="default">
							<template #append>
								<el-button size="default" type="primary" @click="sub" :disabled="!!disabled">
									{{ disabled ? disabled : "获取验证码" }}
								</el-button>
							</template>
						</el-input>
					</el-form-item>
				</el-form-item>
				<el-form-item label="密码">
					<el-input class="add-user-form-item" v-model="addUserForm.password" placeholder="密码" type="password"
						show-password size="default"></el-input>
				</el-form-item>
				<el-form-item label="分组">
					<el-select size="default" class="add-user-form-item" v-model="addUserForm.teamusergroupid!" clearable
						placeholder="可选分组，非必选">
						<el-option v-for="item in group" :key="item.name" :label="item.name" :value="item.ID!">
						</el-option>
					</el-select>
					<el-form-item label="" label-width="80px">
						<el-button size="default" @click="toEditGroup" type="primary">编辑分组</el-button>
					</el-form-item>
				</el-form-item>
				<el-form-item label="">
					<el-button size="default" @click="addUserSubmit" type="primary">确定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<el-drawer class="my-el-drawer" size="1200px" append-to="#app" v-model="addUserListDialogVisible" title="批量添加"
			@close="closeDrawer">
			<template #header="{ close, titleId, titleClass }">
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					<span :id="titleId" :class="titleClass">批量添加</span>
				</span>
			</template>
			<Addtable v-bind="{ close: isClosed, teamInfo, closeDrawer }" />
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from 'qrcode';
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
	Iobj,
	asyncSelectPackageCatebagRelation,
	asyncfindteamusergroup, asyncgetregistphoneVerificationCode, asyncgetteam,
	asyncselectteamcoursegroup,
	asyncselectteamuser, asyncteamdelteamuser, asyncteamresetpassword, asyncuserregist
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import { default as Studycodemodel, default as study } from "../../../mysql_interface/studycodemodel";
import { getGroupedByCatebagArr } from "../../../util/cloudClass";
import mergeImages from "../../../util/merge-images";
import { toLocaleString } from "../../../util/time";
import { courseCatebag } from "../data/data";
import Addtable from "../User/addtable.vue";
import Adduser from "./adduserteam.vue";

const defaultPIDs = courseCatebag.map(e => (e.pID))

const st: Record<any, any> = {
	"0": "成员",
	"1": "用户申请中",
	"2": "管理员邀请中",
	"3": "拒绝加入",
};
const admin: Record<any, any> = {
	'0': '团员',
	'1': '管理员',
	'2': '教师'
}
const type = [
	{ label: "团员", value: "0" },
	{ label: "管理员", value: "1" },
	{ label: "教师", value: "2" },
]
const router = useRouter()
const route = useRoute()
const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
	return store.getters.getuser;
});
const teamId = computed(() => {
	return Number(user.value?.teamid)
})
const onlineUser = computed(() => {
	return store.state.onlineUser || [];
})

const userList = ref<Studycodemodel.Iteamuser[]>([]);
const count = ref(0);
const limit = ref(20)
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const offset = ref(0)

const uID = ref(0);
// 添加成员组件
const adduserview = ref();
const teamuser = computed(() => {
	if (uID.value) return userList.value.find((v) => v.ID == uID.value);
	return {};
});

onMounted(() => {
	start();
});
const tableData = computed(() => {
	return userList.value.map(e => {
		let onlineRet = onlineUser.value.find(olU => olU.userid === e.userid)
		return { ...e, online: !!onlineRet }
	})
})

const selectGroup = computed(() => {
	return [{ ID: '全部', name: '全部' }, { ID: '未分组', name: '未分组' }, ...group.value]
})
const teamInfo = ref<Studycodemodel.Iteam>({})
const group = ref<Studycodemodel.Iteamusergroup[]>([])
const teamusergroupid = ref()
const userid = ref()
const username = ref()
const userisAdmin = ref()
async function start() {
	// 获取团队信息
	teamInfo.value = await asyncgetteam({ ID: teamId.value });
	// 获取团队分组
	group.value = await asyncfindteamusergroup({ teamid: teamId.value });
	// 获取团队成员
	let cond: Iobj<Studycodemodel.Iteamuser> = {
		userid: userid.value,
		isAdmin: userisAdmin.value,
		teamid: teamId.value,
		_limit: limit.value,
		_offset: offset.value,
	}
	// 模糊查询 username
	if (username.value) {
		cond._like = ["username", username.value]
	}
	let groupId = teamusergroupid.value === '未分组' ? null : teamusergroupid.value
	if (groupId !== '全部') { cond.teamusergroupid = groupId }
	const data = await asyncselectteamuser(cond);
	userList.value = data.rows;
	count.value = data.count;
}

// 编辑
function edit(ID: number) {
	if (adduserview.value) {
		adduserview.value.setdialogVisible(true);
		uID.value = ID;
	}
}

// formatter
function formatGroupName(teamusergroupid: number) {
	const d = group.value?.find((v: study.Iteamusergroup) => v.ID == teamusergroupid);
	if (d) {
		return d.name;
	}
	return '未分组'
}
function formatDate(updatedAt: string | number | Date) {
	return toLocaleString(updatedAt);
}
function handleCurrentChange(val: number) {
	offset.value = limit.value * (val - 1);
	start()
}
const handleSizeChange = (val: number) => {
	limit.value = val
	start()
}

// 重置pwd
async function resetPwd(info: study.Iteamuser) {
	// 增加确认框
	ElMessageBox.confirm(
		'是否重置该成员密码?', "警告",
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning', draggable: true, buttonSize: 'default'
		}
	)
		.then(() => {
			asyncteamresetpassword({ ID: info.userid!, teamid: info.teamid! }).then(() => {
				ElMessage.success("密码已被重置为 “000000”");
			}).catch(e => {
				ElMessage.error(e);
			})
		})
		.catch(() => {
			console.log("取消重置成员密码")
		})
}

// 删除成员
async function delteamuser(ID: number) {
	ElMessageBox.confirm("确定要移除此成员吗", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(() => {
			asyncteamdelteamuser({ ID, teamid: teamId.value })
				.then(() => {
					ElMessage.success("移除成功");
					start();
				})
				.catch((e) => {
					ElMessage.error("移除失败" + e);
				});
		})
		.catch(() => { });
}

// 邀请成员 
const dialogVisibleInvited = ref(false)
const dialogVisibleImage = ref(false)
const userId = ref<number | string>("");
// 课程包
const courseCatebags = ref<number[]>([])
// 邀请成员团队组
const invitedGroup = ref()
const invitedLoading = ref(false)
async function invited() {
	courseCatebags.value = []
	dialogVisibleInvited.value = true
	invitedLoading.value = true
	try {
		// 获取团队代理商课包
		const { rows, count } = await asyncselectteamcoursegroup({ teamid: teamId.value })
		// 没有查到就用前端默认的7个代理商课包
		const pIds = rows?.length ? rows.map(e => Number(e.coursegroupid)) : defaultPIDs
		// 代理商课包-课程组
		await getPackageCatebagRelation(pIds)
		invitedLoading.value = false
	} catch (error) {
		console.error("invited catch error=>", error)
		invitedLoading.value = false
	}
}
// 代理商课包-课程组关系
const allCourseCatebags = ref<Alymodel.GroupedByCatebag[]>([])
// 获取指定代理商课包 =》 课程 =》 课程组 关系 
const teamPackageCatebagRelation = ref<Alymodel.PackageCatebagRelation[]>([])
async function getPackageCatebagRelation(pID: number[]) {
	const { rows: data, count } = await asyncSelectPackageCatebagRelation({ ID: pID, })
	teamPackageCatebagRelation.value = data
	// 按课程包分组
	allCourseCatebags.value = getGroupedByCatebagArr(data)
}

function showQrCode() {
	dialogVisibleImage.value = true
	setTimeout(() => {
		const query = `teamid=${teamInfo.value?.ID}&teamusergroupid=${invitedGroup.value}&catebagids=${courseCatebags.value}`
		console.log("===", `https://oj.hterobot.com/h51.html?${query}`)
		QRCode.toDataURL(`https://oj.hterobot.com/h51.html?${query}`, {
			type: 'image/png',
			width: 500,
		},
			async (err, url) => {
				const mig = await fetch('https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/join_team_bg.png')
				const n = await mig.blob()
				const fileReader = new FileReader()
				fileReader.readAsDataURL(n)
				fileReader.onloadend = (e) => {
					var result = e.target?.result as string
					mergeImages([
						{ src: result },
						{ src: url, x: 250, y: 750 },
						{ src: String(teamInfo.value?.name), format: 'text', fontSize: '50px', color: '#fff', x: 150, y: 400 },
						{ src: `欢迎你的加入！`, fontSize: '80px', color: '#fff', x: 150, y: 520, format: 'text' },
						{ src: '扫码注册 自动加入团队', fontSize: '48px', color: '#fff', x: 250, y: 700, format: 'text' }
					],
						{ width: 1000, height: 1778, }).then(e => {
							const canvasimage = document.getElementById("canvasimage") as HTMLImageElement
							if (canvasimage) {
								canvasimage.src = e as string
							}
						})
				}
			}
		)
	}, 100);
}

// 添加成员
const addUserDialogVisible = ref(false)
const addUserForm = ref({
	teamid: teamId.value,
	name: "",
	phonenum: "",
	yzm: "",
	password: '123456',
	teamusergroupid: null,
})
// 验证码
const disabled = ref(0);
let timer = 0;
function time() {
	disabled.value = 60;
	timer = window.setInterval(() => {
		disabled.value = disabled.value - 1;
		if (disabled.value === 0) {
			window.clearInterval(timer);
		}
	}, 1000);
}
async function sub() {
	console.log(addUserForm.value.phonenum)
	if (addUserForm.value.phonenum) {
		try {
			await asyncgetregistphoneVerificationCode(addUserForm.value.phonenum);
			ElMessage.success("发送成功");
			time();
			setTimeout(() => {
			}, 300);
		} catch (error) {
			ElMessage.error(error);
		}
	}
}
async function addUserSubmit() {
	addUserForm.value.username = addUserForm.value.name;
	try {
		await asyncuserregist(addUserForm.value);
		ElMessage.success("添加成功");
	} catch (e: any) {
		ElMessage.error(e);
	}
}

const emit = defineEmits(["update:tabName"]);
function toEditGroup() {
	addUserDialogVisible.value = false
	emit('update:tabName', '团队用户组')
}

// 批量添加
const addUserListDialogVisible = ref(false)
const isClosed = ref(false)
watch(() => addUserListDialogVisible.value, (v) => {
	isClosed.value = v
})
function closeDrawer() {
	addUserListDialogVisible.value = false
	store.state.socket.removeListener('api_import_user')
}
</script>

<style scoped>
.header {
	display: flex;
	/* align-items: center; */
	justify-content: space-between;
}

.online-container {
	display: flex;
	align-items: center;
	/* justify-content: flex-start; */
}

.online-svg {
	width: 35%;
	text-align: end;
	margin-right: 10px;
}

.username {
	width: 65%;
	/* line-height: 14px; */
	display: inline-block;
	vertical-align: middle;
	text-align: start;
}

#canvasimage {
	object-fit: cover;
	display: inline-block;
	margin: auto;
}

.pager {
	margin-top: 10px;
	margin-right: 0;
	float: right;
}
</style>
<style>
.image-dialog1 .el-dialog__header {
	display: none !important;
}

.image-dialog1 .el-dialog__body {
	padding: 0 !important;
}

.image-dialog1 {
	--el-dialog-bg-color: rgba(0, 0, 0, 0) !important;
}

.add-user-form-item {
	width: 220px
}
</style>